package com.lhl.forum.service.impl;

import com.lhl.forum.common.AppResult;
import com.lhl.forum.common.ResultCode;
import com.lhl.forum.dao.ArticleMapper;
import com.lhl.forum.exception.ApplicationException;
import com.lhl.forum.model.Article;
import com.lhl.forum.model.Board;
import com.lhl.forum.model.User;
import com.lhl.forum.service.IArticleService;
import com.lhl.forum.service.IBoardService;
import com.lhl.forum.service.IUserService;
import com.lhl.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;


    @Override
    public void create(Article article) {
        //非空校验
        if (article == null || article.getUserId() == null || article.getBoardId() == null
             || StringUtil.isEmpty(article.getTitle())
             || StringUtil.isEmpty(article.getContent())){

            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //设置默认值
        article.setVisitCount(0);   //访问数
        article.setReplyCount(0);   //回复数
        article.setLikeCount(0);    //点赞数
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

       //写入数据库
        int insertRow = articleMapper.insert(article);

        //判断是否写入成功
        if (insertRow <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + ", userId = " + article.getUserId() +" boardId = " + article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //获取版块信息
        Board board = boardService.selectById(article.getBoardId());
        //数据库中是否存在该板块
        if (board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ", 版块不存在，boardId = " + article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //更新版块帖子数
        boardService.addOneArticleCountById(article.getBoardId());


        //获取用户信息
        User user = userService.selectById(article.getUserId());
        //数据库中是否存在该板块
        if (user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ",发帖失败，userId = " + article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //更新用户帖子数
        userService.addOneArticleCountById(article.getUserId());

        //打印成功信息
        log.info(AppResult.success().toString() + ", userId = " + article.getUserId() +
                ", boardId = " + article.getTitle() + ", articleId = " + article.getId() + ", 帖子发布成功");
    }

    @Override
    public List<Article> selectAll() {

        //调用dao层查询数据
        List<Article> articles = articleMapper.selectAll();

        //返回查询结果
        return articles;
    }

    @Override
    public List<Article> selectById(Long boardId) {

        //非空校验
        if (boardId == null || boardId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //根据版块id查询版块
        Board board = boardService.selectById(boardId);
        //版块是否存在
        if (board == null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        //调用dao层查询数据
        List<Article> articles = articleMapper.selectById(boardId);

        //返回查询结果
        return articles;
    }


    //根据帖子id查询详情(访问帖子详情)
    @Override
    public Article selectDetailById(Long id) {

        //非空校验
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询信息
        Article article = articleMapper.selectDetailById(id);

        //校验帖子是否存在
        if (article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //更新帖子的访问次数
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount() + 1);

        //将数据写入数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);

        //判断数据是否写入成功
        if ( row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //当点击帖子访问的时候，帖子的访问量已经更新
        article.setVisitCount(article.getVisitCount() + 1);

        //返回查询结果
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if (id == null || title == null || content == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + "修改帖子失败，参数校验不成功");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //对帖子进行修改
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        article.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(article);

        //判断是否更新成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + "帖子修改失败");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public Article selectByArticledId(Long id) {
        //非空判断
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //进行数据查询
        Article article = articleMapper.selectByPrimaryKey(id);

        return article;
    }

    @Override
    public void thumbsUp(Long id) {
        //非空校验
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);

        //判断帖子是否存在
       if (article == null){
           //打印日志
           log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
           //抛出异常
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
       }

        //判断帖子是否正常
        if (article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setUpdateTime(new Date());

        //更新点赞数
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //是否更新成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void deleteById(Long id) {
        //非空校验
        if (id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断帖子是否存在
        if (article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断帖子当前的状态
        if (article.getDeleteState() == 1 || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //更新帖子状态
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte)1);

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //判断是否更新成功
        if (article.getDeleteState() == 1 || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //更新用户帖子数量
        Long userId = article.getUserId();
        userService.subOneArticleCountById(userId);

        //更新版块帖子数量
        Long boardId = article.getBoardId();
        boardService.subOneArticleCountById(boardId);
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");

    }
}
